package msg.model;

import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.net.InetAddress;
import msg.udp.UDPClient;
import msg.view.ClientView;


public class AppClient {

	private Mediator mediator;
	private UDPClient udpClient;
	private ClientView clientView;

	private String serverIp;
	private int serverPort;

	private String message;
	private String userName;
	private String userIp;
	private int userPort;


	public AppClient(ClientView clientView) {
		this.clientView = clientView;
		this.mediator = new MediatorImpl();
	}


	public void connect(String userName, String serverIp, int serverPort) {
		this.serverIp = serverIp;
		this.serverPort = serverPort;
		this.userName = userName;

		this.udpClient = new UDPClient(clientView);
		this.userIp = this.getLocalIP();
		this.userPort = udpClient.getLocalPort();

		this.mediator.register(this);
		this.send("<serv>", "<hi>");
		this.udpClient.start();
	}


	public void send(String to, String msg) {
		this.message = this.userIp + "`" + this.userPort + "`" + this.userName + "`" + to + "`" + msg;
		this.mediator.send(this.serverIp, this.message);
	}


	/** method checks length of text box */
	public void checkLength(String txt, int max, KeyEvent ke) {
		if ((txt.length() >= max)) {
			Toolkit.getDefaultToolkit().beep();
			ke.consume();
		}
	}


	/** method gets system IP address */
	public String getLocalIP() {
		try {
			return InetAddress.getLocalHost().getHostAddress();

		} catch (Exception ex) {
			System.err.println("IP default error!");
			System.err.println("Error message: " + ex.getMessage());
			return "";
		}
	}


	public String getServIp() {
		return this.serverIp;
	}

	public int getServPort() {
		return this.serverPort;
	}
}